package com.iyunwen.datatool.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iyunwen.datatool.dao.EventDataMapper;
import com.iyunwen.datatool.model.dbdo.EventDataDO;
import com.iyunwen.datatool.model.flow.PageResult;
import com.iyunwen.datatool.model.vo.EventGroupVO;
import com.iyunwen.datatool.rule.ISignalAttentionRuleEngine;
import com.iyunwen.datatool.service.IDataLoadService;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description:
 * @author: Zhu.Guodong
 * @create: 2020-03-17 10:25
 * @version:
 */
@Slf4j
@Service
public class DataLoadServiceImpl implements IDataLoadService {

    @Autowired
    EventDataMapper eventDataMapper;
    @Autowired
    ISignalAttentionRuleEngine ruleEngine;


    @Override
    public List<File> readHtmlFile(String path) {
        File fileDirection = new File(path);
        if (fileDirection.exists() && fileDirection.isDirectory()) {
            File[] files = fileDirection.listFiles();
            return Arrays.asList(files);
        }
        return null;
    }

    @Override
    public List<EventDataDO> readSignalDataFromHtml(File file) {
        List<EventDataDO> eventDataDOList = new ArrayList<>();
        try {
            Document doc = Jsoup.parse(file, "UTF-8", "");
            Element body = doc.body();
            String bodyTitleStr = body.childNodes().get(0).outerHtml();
            log.info("读取文件:{},标题:{}", file.getName(), bodyTitleStr);
            //表格对象
            Elements table_tr = doc.select("table tr");
            //表数据
            for (int i = 0; i < table_tr.size(); i++) {
                if (0 == i) {
                    continue;
                }
                EventDataDO eventDataDO = new EventDataDO();

                Element itemTr = table_tr.get(i);
                //背景色
                String bgcolor = itemTr.attr("bgcolor");
                eventDataDO.setBackgroundColor(bgcolor);

                Elements tdElements = itemTr.getElementsByTag("td");
                //行记录数据集合
                List<String> tdStrList = new ArrayList<>();
                for (int tdIndex = 0; tdIndex < tdElements.size(); tdIndex++) {
                    Element itemTd = tdElements.get(tdIndex);
                    String itemTdStr = itemTd.text();
                    tdStrList.add(itemTdStr);
                    if (tdIndex == 0) {
                        continue;
                    }
                    switch (tdIndex) {
                        case 0:
                            break;
                        case 1:
                            SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd,HH:mm:ss:SSS");
                            try {
                                Date parseDate = sdf.parse(itemTdStr);
                                //Timestamp timestamp = new Timestamp(parseDate.getTime());
                                eventDataDO.setEventTime(parseDate.getTime());
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            break;
                        case 2:
                            eventDataDO.setEventType(itemTdStr);
                            break;
                        case 3:
                            eventDataDO.setMasterOrSlave(itemTdStr);
                            break;
                        case 4:
                            eventDataDO.setEventNumber(itemTdStr);
                            break;
                        case 5:
                            eventDataDO.setEventSource(itemTdStr);
                            break;
                        case 6:
                            eventDataDO.setEventDesc(itemTdStr);
                            break;
                        case 7:
                            eventDataDO.setEventLevel(itemTdStr);
                            break;
                        case 8:
                            eventDataDO.setEventStatus(itemTdStr);
                            break;
                        case 9:
                            eventDataDO.setDuration(itemTdStr);
                            break;
                        case 10:
                            eventDataDO.setDeviceDescription(itemTdStr);
                            break;
                        case 11:
                            eventDataDO.setOperator(itemTdStr);
                            break;
                        case 12:
                            eventDataDO.setConformPerson(itemTdStr);
                            break;
                        default:
                            break;
                    }
                }
                boolean attentionSignal = ruleEngine.isAttentionSignal(eventDataDO);
                if (attentionSignal) {
                    //System.out.println(eventDataDO);
                }
                eventDataDOList.add(eventDataDO);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return eventDataDOList;
    }

    @Override
    public boolean createTable(String tableName) {
        eventDataMapper.createTable(tableName);
        return true;
    }

    @Override
    public boolean insertSignalDataToDatabase(List<EventDataDO> eventData,String tableName) {
        eventDataMapper.insertBatch(eventData,tableName);
        return true;
    }

    @Override
    public EventDataDO readIndexSignalDataFromDb(Long index) {
        return null;
    }

    @Override
    public PageResult<EventDataDO> getEventData(int pageNum, int pageSize,String tableName) {
        PageHelper.startPage(pageNum,pageSize);
        List<EventDataDO> list = eventDataMapper.selectNoticeData(tableName);
        PageInfo<EventDataDO> pageInfo = new PageInfo<>(list);
        PageResult<EventDataDO> pageResult = new PageResult<>(pageInfo.getList(),pageInfo.getTotal());
        return pageResult;
    }

    @Override
    public List<EventDataDO> readSignalDataFromDb(EventDataDO eventDataDO, int rangTime,String tableName) {
        Timestamp timestamp = new Timestamp(eventDataDO.getEventTime());
        String str = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS").format(timestamp);
        List<EventDataDO> list = eventDataMapper.selectRangeData(tableName,str,rangTime);
        return list;
    }

    @Override
    public void distinctEventGroup(List<EventGroupVO> eventGroupList) {

    }

    @Override
    public EventGroupVO getHighLevelSignalDataNotInGroup() {
        return null;
    }

    @Override
    public void writeEventGroupDataToExcel(List<EventGroupVO> eventGroupData) {

    }


    public static void main( String args[] ){
        String REGEX = ".*切换.*系统.*";
        String input = "切换系统";
        Pattern p = Pattern.compile(REGEX);
        Matcher m = p.matcher(input); // 获取 matcher 对象
        boolean matches = m.matches();
        System.out.println(matches);
        int count = 0;

        while(m.find()) {
            count++;
            System.out.println("Match number "+count);
            System.out.println("start(): "+m.start());
            System.out.println("end(): "+m.end());
        }
    }

//    public static void main(String[] args) {
//        String time = "***2017-06-24,00:47:10:240*";
//        String REGEX = "[^0-9]+";
//        String replace = time.replaceAll(REGEX, "-");
//        if (replace.startsWith("-")){
//            replace = replace.substring(1);
//        }
//        if (replace.endsWith("-")) {
//            replace = replace.substring(0,replace.length() - 1);
//        }
//        SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS");
//        try {
//            Date parseDate = sdf.parse(replace);
//            System.out.println(parseDate);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        System.out.println(replace);
//    }
}
